package com.weedsdream.fileselect

import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.provider.MediaStore
import android.widget.ImageView
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.engine.CropFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener
import com.luck.picture.lib.interfaces.OnMediaEditInterceptListener
import com.luck.picture.lib.interfaces.OnRecordAudioInterceptListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.utils.ActivityCompatHelper
import com.weedsdream.BaseActivity
import com.weedsdream.function.toast
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.UCropImageEngine
import java.io.File

object ImageSelector {

    /**预览
     * @param srcMedias 旧有的数据列表
     * @param position 预览文件在源数据的位置
     * @param onPreviewDelete 删除回调,若与onLongPressDownload有一个不为空，都会开启事件
     * @param onLongPressDownload 长按下载回调,若与onPreviewDelete有一个不为空，都会开启事件*/
    fun previewPicture(
        srcMedias: MutableList<LocalMedia>,
        position: Int,
        onLongPressDownload: ((context: Context?, media: LocalMedia?) -> Unit)? = null,
        onPreviewDelete: ((position: Int) -> Unit)? = null,
    ) {
        val list = srcMedias.toCollection(ArrayList())
        //预览
        PictureSelector.create(BaseActivity.activity).openPreview()//
            .setImageEngine(GlideEngine.createGlideEngine())//
            .isUseSystemVideoPlayer(true)//使用系统播放器
            .isVideoPauseResumePlay(true)//
            .let {
                if (onPreviewDelete != null || onLongPressDownload != null) {
                    it.setExternalPreviewEventListener(object : OnExternalPreviewEventListener {
                        override fun onPreviewDelete(position: Int) {
                            if (onPreviewDelete != null) onPreviewDelete(position)
                        }

                        override fun onLongPressDownload(
                            context: Context?, media: LocalMedia?
                        ): Boolean {
                            if (onLongPressDownload != null) onLongPressDownload(context, media)
                            return false
                        }
                    })
                }
                it
            }.startActivityPreview(position, true, list)
    }


    /**打开图片选择器
     * @param srcMedias 旧有的可Ui监视的列表
     * @param selectMimeType 画廊类型，使用SelectMimeType参数
     * @param selectModeConfig 选择模式：单选还是多选
     * @param selectNum 可选数量，分别为最小，最大
     * @param selectFileSize 文件大小限制，分别为最小，最大
     * @param filterFileSize 文件大小筛选，分别为最小，最大
     * @param filterVideoSecond 过滤视频时长，分别为最小，最大
     * @param selectDurationSecond 根据时长筛选视频或音频，分别为最小，最大
     * @param recordVideoSecond 视频录制时长限制，分别为最小，最大
     * @param videoSelectNum 视频选择数量限制，分别为最小，最大
     * @param audioMinSelectNum 音频最小选择数量限制
     * @param requestedOrientation 屏幕方向
     * @param onCancel 取消回调
     * @param onResult 结果回调*/
    fun openPicture(
        srcMedias: MutableList<LocalMedia>? = null,
        selectMimeType: Int = SelectMimeType.TYPE_ALL,
        selectModeConfig: Int = SelectModeConfig.MULTIPLE,
        selectNum: Pair<Int, Int>? = null,
        selectFileSize: Pair<Long, Long>? = null,
        filterFileSize: Pair<Long, Long>? = null,
        filterVideoSecond: Pair<Int, Int>? = null,
        selectDurationSecond: Pair<Int, Int>? = null,
        recordVideoSecond: Pair<Int, Int>? = null,
        videoSelectNum: Pair<Int, Int>? = null,
        audioMinSelectNum: Int? = null,
        requestedOrientation: Int = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
        onCancel: () -> Unit = {},
        onResult: (result: ArrayList<LocalMedia>) -> Unit,
    ) {
        PictureSelector.create(BaseActivity.activity)//
            .openGallery(selectMimeType)//
            .setImageEngine(GlideEngine.createGlideEngine())//设置图片加载引擎
            .isDisplayCamera(true)//显示拍照功能
            .isFastSlidingSelect(true)//滑动选择
            .isDisplayTimeAxis(true)//显示时间轴
            .isMaxSelectEnabledMask(true)//显示不可选蒙层
            .isPreviewImage(false)//点击图片预览
            .isPreviewVideo(true)//点击视频预览
            .isPreviewAudio(true)//点击音频预览
            .isLoopAutoVideoPlay(true)//音视频循环播放
            .isVideoPauseResumePlay(true)//视频允许暂停续播
            .isGif(true)//显示gif
            .isWebp(true)//显示webp格式
            .isBmp(true)//显示bmp格式
            .isHeic(true)//显示heic格式
            .setLanguage(LanguageConfig.SYSTEM_LANGUAGE).isEmptyResultReturn(true)//支持未选择返回
            .isOpenClickSound(false)//是否开启点击音效
            .setRecordAudioInterceptListener(recordAudioInterceptListener)//录音意图
            .setEditMediaInterceptListener(editorMediaListener)//编辑功能
            .setSelectionMode(selectModeConfig)//单选还是多选
            .isWithSelectVideoImage(true)//是否支持视频图片同选
            .isOriginalSkipCompress(true)//选择原始图像以跳过压缩
            .isAutomaticTitleRecyclerTop(true).isPreloadFirst(true)//
            .isSyncCover(true).isSyncWidthAndHeight(true)
            .setRequestedOrientation(requestedOrientation)//
            .let {
                if (srcMedias != null) it.setSelectedData(srcMedias)//
                if (selectMimeType != SelectMimeType.TYPE_AUDIO) it.isOriginalControl(true)//允许上传原图
                selectNum?.apply {//可选数量限制
                    it.setMinSelectNum(first)
                    it.setMaxSelectNum(second)
                }
                selectFileSize?.apply {//文件大小限制
                    it.setSelectMinFileSize(first)
                    it.setSelectMaxFileSize(second)
                }
                filterFileSize?.apply {//文件大小筛选
                    it.setFilterMinFileSize(first)
                    it.setFilterMaxFileSize(second)
                }
                filterVideoSecond?.apply {
                    it.setFilterVideoMinSecond(first)//过滤视频最小时长
                    it.setFilterVideoMaxSecond(second)//过滤视频最大时长
                }
                selectDurationSecond?.apply {//限制视频的时长
                    it.setSelectMinDurationSecond(first)
                    it.setSelectMaxDurationSecond(second)
                }
                recordVideoSecond?.apply {//限制视频录制时长
                    it.setRecordVideoMinSecond(first)
                    it.setRecordVideoMaxSecond(second)
                }
                videoSelectNum?.apply {//视频选择数量
                    it.setMinVideoSelectNum(first)
                    it.setMaxVideoSelectNum(second)
                }
                audioMinSelectNum?.apply {//音频最少数量限制
                    it.setMinAudioSelectNum(this)
                }
                it
            }.forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    onResult(result ?: arrayListOf())
                }

                override fun onCancel() {
                    onCancel()
                }
            })
    }


    /**编辑事件*/
    private val editorMediaListener =
        OnMediaEditInterceptListener { fragment, localMedia, requestCode ->
            if (localMedia.mimeType.startsWith("video")) {
                toast("视频编辑功能未实现")
            } else {
                val path = localMedia.getAvailablePath()
                val sourceUri =
                    if (path.startsWith("content://")) Uri.parse(path) else Uri.fromFile(
                        File(path)
                    )
                val destinationUri = Uri.fromFile(
                    File(
                        fragment.requireContext().cacheDir, "${System.currentTimeMillis()}.jpg"
                    )
                )
                UCropEngine.cropImageEngine(sourceUri, destinationUri)
                    .startEdit(fragment.requireContext(), fragment, requestCode)
            }
        }

    /**录音意图*/
    private val recordAudioInterceptListener =
        OnRecordAudioInterceptListener { fragment, requestCode ->
            val recordAudioIntent = Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION)
            if (recordAudioIntent.resolveActivity(
                    fragment.requireActivity().packageManager
                ) != null
            ) {
                fragment.startActivityForResult(recordAudioIntent, requestCode)
            } else {
                toast("The system is missing a recording component")
            }
        }

    /**
     * @author：luck
     * @date：2022-5-24 22:30
     * @describe：图片裁剪
     */
    private class UCropEngine : CropFileEngine {
        companion object {
            fun cropImageEngine(srcUri: Uri, destinationUri: Uri): UCrop {
                val uCrop = UCrop.of<UCrop>(srcUri, destinationUri)
                uCrop.setImageEngine(object : UCropImageEngine {
                    override fun loadImage(
                        context: Context, url: String, imageView: ImageView
                    ) {
                        if (!ActivityCompatHelper.assertValidRequest(context)) {
                            return
                        }
                        Glide.with(context).load(url).override(180, 180).into(imageView)
                    }

                    override fun loadImage(
                        context: Context,
                        url: Uri,
                        maxWidth: Int,
                        maxHeight: Int,
                        call: UCropImageEngine.OnCallbackListener<Bitmap>?
                    ) {
                        if (!ActivityCompatHelper.assertValidRequest(context)) {
                            return
                        }
                        Glide.with(context).asBitmap().load(url).override(maxWidth, maxHeight)
                            .into(object : CustomTarget<Bitmap?>() {

                                override fun onLoadFailed(errorDrawable: Drawable?) {
                                    call?.onCall(null)
                                }

                                override fun onResourceReady(
                                    resource: Bitmap, transition: Transition<in Bitmap?>?
                                ) {
                                    call?.onCall(resource)
                                }

                                override fun onLoadCleared(placeholder: Drawable?) {
                                    call?.onCall(null)
                                }
                            })
                    }
                })
                return uCrop
            }
        }

        override fun onStartCrop(
            fragment: Fragment?,
            srcUri: Uri?,
            destinationUri: Uri?,
            dataSource: ArrayList<String>?,
            requestCode: Int
        ) {
            if (srcUri == null && destinationUri == null && fragment == null) return
            cropImageEngine(srcUri!!, destinationUri!!).start(
                fragment!!.requireContext(), fragment, requestCode
            )
        }
    }
}
